<?php

namespace app\admin\controller\survey;

use app\admin\model\survey\Data as SurveyData;
use app\admin\model\survey\RecordsAnswer;
use app\admin\model\User;
use app\common\controller\Backend;
use think\exception\DbException;
use think\response\Json;

/**
 * 问卷记录管理
 *
 * @icon fa fa-circle-o
 */
class Records extends Backend
{

    /**
     * Records模型对象
     * @var \app\admin\model\survey\Records
     */
    protected $model = null;
	protected $relationSearch = true;
	protected $searchFields = ['customer.name','user.phone'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\survey\Records;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

	/**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
			$getShowQuestion = $this->getShowQuestion(1);
			$this->assignconfig('showQuestion', $getShowQuestion);

            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

		$authWhere = [];
		if(!$this->auth->isSuperAdmin()){
			$uids = User::where(['spread_uid'=>$this->auth->uid])->column('uid');
			$authWhere['records.uid'] = ['in', $uids];
		}

        $list = $this->model->alias('records')->with(['customer','user','answer'])
            ->where($where)->where($authWhere)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

	protected function getShowQuestion($survey_id = 0){
		switch ($survey_id){
			case 1:
				$questions = [1,2,3,6,11,22,24];
				break;
			default:
				$questions = [];
				break;
		}

		if (count($questions) > 0) $questions = SurveyData::where(['id' => ['in', $questions]])->select();
		return $questions;
	}

	public function answers($id){
		$row = $this->model->find($id);
		if(!$row) $this->error('问卷不存在');
		$this->assign('row', $row);

		$answers = RecordsAnswer::getList($row->id);
		$this->assign('answers', $answers);

		return $this->fetch();
	}
}
